# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: jaewon

from typing import List, Union

from coin.base.param_util import to_list
from coin.exchange.base.kr_rest.product import NormProduct
from coin.exchange.base.kr_rest.futures_product import NormFuturesProduct

import coin.exchange.bitflyer_v1.config as bitflyer_config
from coin.exchange.bitflyer_v1.kr_rest.futures_product import (BitflyerFuturesProduct)
from coin.exchange.bitflyer_v1.kr_rest.product import BitflyerProduct


def get_native_symbol(product):
  if isinstance(product, BitflyerFuturesProduct):
    return BitflyerFuturesProduct.FromProduct(product).native_symbol
  elif isinstance(product, BitflyerProduct):
    return BitflyerProduct.FromProduct(product).native_symbol
  else:
    raise ValueError(product)


def _get_feed_group(product, feed_group_finder):
  if product is None:
    groups = ['*']
  else:
    product = to_list(product)
    groups = sorted({feed_group_finder(p) for p in product})
  return groups


def find_feed_group(product):
  native_symbol = get_native_symbol(product)
  for group, native_symbol_list in bitflyer_config.group_symbol.items():
    if native_symbol in native_symbol_list:
      return group
  raise ValueError(native_symbol)


def get_topic_string(product: Union[NormFuturesProduct, List[NormFuturesProduct], None],
                     worker_id='1'):
  groups = _get_feed_group(product, find_feed_group)
  topics = []
  for g in groups:
    topics += [
        'bitflyer_ws_ticker_board_%s%s' % (g, worker_id),
    ]
  return topics
